package indi.utils;

import indi.imooc.algorithm.sortInterface.SortInterface;

/**
 * 辅助验证排序算法是否正确
 */
public class SortingHelper {
    private SortingHelper(){};
    public static <E extends Comparable<E>> boolean isSorted(E[] e){
        if (e.length <= 1){
            return true;
        }
        for (int i = 0; i < e.length - 1; i++) {
            if (e[i + 1].compareTo(e[i]) < 0){
                return false;
            }
        }
        return true;
    }

    /**
     * 算法测试
     * @param <E>
     */
    public static <E extends Comparable<E>> void testSort(Class clz,String sortName,E[] arr){
        long startTime = System.nanoTime();
        try {
            SortInterface sortInterface = (SortInterface) clz.newInstance();
//            Method m = clz.getDeclaredMethod("sort",new Class[]{arr.getClass()});
//            Method m = clz.getDeclaredMethod("sort",arr.getClass());
//            m.invoke(obj,arr);
            sortInterface.sort3(arr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long endTime = System.nanoTime();
        double time = (endTime - startTime)/1000_000_000.0;

        boolean res = isSorted(arr);
        if (!res){
            throw  new RuntimeException("selectionSort fail");
        }

        System.out.println(String.format("%s: n = %d, 执行时间 = %f s", sortName,arr.length,time));
    }
}
